package com.final_project.zombiemenace.highscore;

import android.widget.ScrollView;
import android.widget.TextView;

public class HighScoreThread implements Runnable {

	ScrollView scroll;
	TextView highScoreText;
	private static volatile boolean running;
	
	public HighScoreThread(ScrollView scroll,TextView textViewInScroll) {
		this.scroll = scroll;
		this.highScoreText = textViewInScroll;
		running = true;
	}
	
	/**
	 * When this method is called it stops the current thread by  changing
	 * the value of the  running boolean variable to stop which causes
	 * the run method to end
	 */
	public static void stop() {
		running = false;
	}
	
	
	@Override
	public void run() {
		sleep(1500);
		// the value for the Scrolling increaser or decreaser (down or up)
		int i = -1;
		while (running) {
			if(hasReachedTop()&& i < 1){
				// increase by two, so that the scrollig to be with +1 pixel by Y
				//only if the scrolling is lesser than 0
				i+=2;
			}
			if(hasReachedBottom() && i > 0){
				// decrease by two, so that the scrollig to be with -1 pixel by Y
				//only if the scrolling is bigger than 0
				i-=2;
			}
			//Scrolling
			scroll.smoothScrollBy(0, i);
			// little slow down after each scroll
			sleep(100);
		}
	}

	/**
	 * Determines if the scroller has reached bottom.
	 * @return true if the top most scroll value plus the height of the scroll 
	 * is equal to the inside view's bottom
	 */
	private boolean hasReachedBottom() {
		return highScoreText.getBottom() <= scroll.getScrollY() + scroll.getHeight();
	}

	/**
	 * Determines if the  scroller has reached the top.
	 * @return - true if Y coordinate of the topmost position of the scroll is  0 , false if it's not
	 */
	private boolean hasReachedTop() {
		return scroll.getScrollY() == 0;
	}

	/**
	 * Sleeps the thread by giving it long value representing the time in milliseconds
	 * @param time - long value representing the time to sleep in milliseconds
	 */
	private void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			//TODO Better Exception handle
			e.printStackTrace();
		}
	}
}
